#include "../LibUtil.h"

LIB_UTIL_NAMESPACE_BEGIN

tDataBuffer::tDataBuffer(byte* inData, size_t dataSize, bool refData)
: ref(refData)
{
	pos = 0;
	size = dataSize;
	if(ref)
	{
		data = inData;
	}
	else
	{
		data = new byte[dataSize];
		memcpy(data, inData, dataSize);
	}
}

tDataBuffer::tDataBuffer(bool refData)
: ref(refData)
{
	data = NULL;
	size = 0;
	pos = 0;
}

tDataBuffer::tDataBuffer(char* szText, bool refData)
: ref(refData)
{
	if(refData)
	{
		data = (unsigned char*)szText;
		size = strlen(szText);
	}
	else
	{
		size = strlen(szText);
		data = new byte[size];
		memcpy(data, szText, size);
	}
}

tDataBuffer::tDataBuffer(const string& text, bool refData)
: ref(refData)
{
	if(refData)
	{
		data = (byte*)text.c_str();
		size = text.length();
	}
	else
	{
		size = text.length();
		data = new byte[size];
		memcpy(data, text.c_str(), size);
	}
}

tDataBuffer::tDataBuffer(const tDataBuffer& buffer, bool refData)
: ref(refData)
{
	pos = 0;
	size = buffer.size;;
	if(refData)
	{
		data = buffer.data;
	}
	else
	{
		data = new byte[size];
		memcpy(data, buffer.data, size);
	}
}

const tDataBuffer& tDataBuffer::operator = (const tDataBuffer& buffer)
{
	SAFE_DELETE_ARRAY(data);
	data = new byte[buffer.size];
	memcpy(data, buffer.data, buffer.size);
	size = buffer.size;
	return *this;
}

tDataBuffer::~tDataBuffer()
{
	if(!ref)
	{
		SAFE_DELETE_ARRAY(data);
	}
	size = 0;
	pos = 0;
}

void tDataBuffer::Release()
{
	SAFE_DELETE_ARRAY(data);
	size = 0;
	pos = 0;
}

string tDataBuffer::ToString()
{
	char* szValue = new char[size + 1];
	memcpy(szValue, data, size);
	szValue[size] = 0;
	string text = szValue;
	
	SAFE_DELETE_ARRAY(szValue);
	return text;
}

LIB_UTIL_NAMESPACE_END